'use client';

import { useActionState, useState, useEffect } from "react";
import { useRouter, } from "next/navigation";
import { useInput } from "../input/input";
import { action } from "../action/action";

export default () => {

    const [seconds, setSeconds] = useState(3);
    const router = useRouter();

    const [_username, username, unCheck] = useInput({ name: 'username' });
    const [_password, password, psCheck] = useInput({ type: 'password', name: 'password' });

    const [state, dispatch, isPending] = useActionState(async (_: LoginResponse | null, formdata: FormData) => await action(formdata), null);
    const { code, msg } = state ?? {};

    useEffect(() => {
        if (code === 0) {
            if (seconds > 0) {
                const timer = setInterval(() => {
                    setSeconds(prevCount => prevCount - 1);
                }, 1000);
                return () => clearInterval(timer);

            } else {
                router.push('/register/login');
            }
        }
    }, [code, seconds, router]);

    return <>
        <div style={{ backgroundColor: '#8BC34A', width: '300px', height: '200px', border: '1px solid black', marginLeft: '1100px', marginTop: '60px' }}>
            {
                isPending ? <div>Loading...</div>
                    : <>
                        {code == 0 ? <p>注册成功, {seconds}秒后自动跳转到登录页...</p>
                            : <div>
                                <p style={{ color: 'red' }}>{msg}</p>

                                <form action={dispatch}>
                                    {username}

                                    {password}

                                    <button type="submit" disabled={!unCheck || !psCheck} style={{ backgroundColor: '#00BCD4', padding: '2px 20px', borderRadius: '5px' }}>
                                        注册
                                    </button>
                                </form>
                            </div>
                        }
                    </>
            }
        </div >
    </>
}